package com.x2.excel.converter;

import cn.hutool.core.util.StrUtil;
import com.x2.excel.utils.DicUtils;
import com.x2.excel.utils.SpringContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;

/**
 * Created by Administrator on 2017-12-28.
 */
@Component
public class Dic2FieldConverter implements ReadConvertible {

    @Autowired
    private SpringContextUtil springContextUtil;

    public Dic2FieldConverter(){

    }

    public Dic2FieldConverter(String dicName, String parentCode){
        this.dicName = dicName;
        this.parentCode = parentCode;
    }

    /**
     * 字段的字典名
     */
    private String dicName;

    /**
     * 字段的字典父类代码
     */
    private String parentCode;

    public String getDicName() {
        return dicName;
    }

    public void setDicName(String dicName) {
        this.dicName = dicName;
    }

    public String getParentCode() {
        return parentCode;
    }

    public void setParentCode(String parentCode) {
        this.parentCode = parentCode;
    }

    @Override
    public Object execRead(String object) throws ParseException {

        String strVal = null;
        try {
            if(object!=null&& StrUtil.isNotEmpty(parentCode)){
                String dicNameStr = object.toString();
                if(dicNameStr.indexOf(",")>0){
                    String[] dicNames = dicNameStr.split(",");
                    if(dicNames.length>0){
                        StringBuffer dicNameSB = new StringBuffer();
                        for(String dicName :dicNames){
                            String dicVal = DicUtils.getDictCodesByPCode(parentCode, dicName);
                            if(StrUtil.isNotEmpty(dicVal)){
                                dicNameSB.append(dicVal).append(",");
                            }
                        }
                        if(StrUtil.isNotEmpty(dicNameSB)){
                            strVal = StrUtil.removeSuffix(dicNameSB.toString(), ",");
                        }
                    }
                }else{
                    String dicVal = DicUtils.getDictCodesByPCode(parentCode, dicNameStr);
                    if(StrUtil.isNotEmpty(dicVal)){
                        strVal = dicVal;
                    }
                }

            }
        }catch (Exception e){
            return strVal;
        }
        return  strVal;
    }
}
